<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<div class="module-filter">
					<label style="margin-right: 10px">{{$t('preview_data.shortName')}}</label>
					<div class="el-select el-select--default">
						<el-input type="text" v-model="params.searchKeywords" :placeholder="$t('formRule.inputPlaceholder')" clearable></el-input>
					</div>
				</div>
				<div class="module-filter btns">
					<el-button type="primary" icon="el-icon-search" @click="upsearch">{{ $t('table_data.searchText') }}</el-button>
					<el-button @click="reset">{{ $t('table_data.resetText') }}</el-button>
					<el-button class="addBtn gptbtn" @click="initiateGPT">{{ $t('short_data.sub_transBtn') }}</el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
      <scTable ref="table" :apiObj="apiObj" row-key="id" stripe border :params="sendParams" :hideSetting="true" :sortType="direction" width="100%" @dataChange="dataChange" :isCover="isCover">
        <el-table-column :label="$t('short_data.table.coverPicture')" width="auto">
          <template #default="scope">
            <img :src="scope.row.coverPicture" style="width: 150px;height: 60px;object-fit: contain;">
          </template>
        </el-table-column>
        <el-table-column :label="$t('short_data.table.shortsName')" width="400">
          <template #default="scope">
            {{ setShortName(scope.row.shortName) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('short_data.table.title')" width="400">
          <template #default="scope">
            {{ setShortName(scope.row.title) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('short_data.formLabel.episode')" prop="episodeNo" width="50">
        </el-table-column>
        <el-table-column :label="$t('short_data.form.shortLanguage')" prop="srtLangNum" width="150">
        </el-table-column>
        <el-table-column :label="$t('preview_data.transcodingStatus')">
					<template #default="scope">
						<span v-if="scope.row.status==1" class="colorGrayText">{{ $t('banner_data.uploadSuccessText') }}</span>
						<span v-if="scope.row.status==2" class="colorGrayText">{{ $t('table_data.statusTranscoding') }}</span>
						<span v-if="scope.row.status==3" class="colorGreenText">{{ $t('table_data.statusSuccess') }}</span>
						<span v-if="scope.row.status==4" class="colorRedText">{{ $t('table_data.statusFailure') }}</span>
					</template>
        </el-table-column>
        <el-table-column :label="$t('short_data.table.updateTime')" prop="createAt" width="auto" sortable></el-table-column>
        <el-table-column :label="$t('table_data.operate')" width="auto">
          <template #default="scope">
            <el-button-group>
              <el-button text type="primary" size="small" @click="table_detail(scope.row, scope.$index)">{{ $t('table_data.detail') }}</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
		</el-main>
		<!-- gpt翻译 -->
		<sCDialog :modelValue="showGptBox" :showFullscreen="false" :showClose="false" width="80%" :close-on-click-modal="false">
      <template v-slot:header>
				<div class="gptheadbox">
					<span class="scdialog-title">{{ type==2?$t('short_data.subtitle.tcTitle'):type==1?$t('short_data.subtitle.localBtn'):$t('short_data.subtitle.add') }}</span>
					<el-button @click="contrastSrt">{{ $t('subtitle_data.translateShowResult') }}</el-button>
				</div>
      </template>
			<div class="gptCont">
				<!-- 字幕对比 -->
				 <div class="allSrtbox" v-if="gptForm.showContrast">
						<div class="form-group">
								<p>{{ $t('subtitle_data.translateBefore') }}</p>
								<el-input v-model="gptForm.originalSrt" type="textarea" :rows="27" resize="none"/>
						</div>
						<div class="form-group">
								<p>{{ $t('subtitle_data.translateBehind') }}</p>
								<el-input v-model="gptForm.srtText" type="textarea" :rows="27" resize="none"/>
						</div>
				 </div>
				<div class="gptleftbox">
					<div class="form-group">
							<label for="srtFile">{{ $t('short_data.sub_file') }}</label>
							<input id="srtFile" multiple ref="srtFile" type="file" @change="inputSrtFileToString" placeholder="select file">
							<el-input v-model="gptForm.srt" type="textarea" :rows="27" />
					</div>
				</div>
				<div class="gptrightbox">
					<div class="form-group-nborder">
							<el-dropdown trigger="click">
								<div>{{ $t('short_data.sub_historyWord') }}<el-icon class="add_icon"><component :is="oicon('el-icon-arrow-down')" /></el-icon></div>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item v-for="(item,index) in gptForm.words" :key="index" @click="gptForm.promptWord=item">
											{{ item }}
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
							<!-- <div class="history">
								<span v-for="(item,index) in gptForm.words" :key="index" @click="gptForm.promptWord=item">{{ item }}</span>
							</div> -->
					</div>
					<div class="form-group">
							<label for="promptWord">{{ $t('short_data.sub_word') }}</label>
							<el-input v-model="gptForm.promptWord" type="textarea" :rows="6" />
					</div>
					<!-- <div class="form-group radio-group">
							<p>源语言：</p>
							<el-radio v-model="gptForm.oldsrtLang" label="en-US">{{ $t('short_data.subtitle.english') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-radio>
					</div> -->
					<div class="form-group">
							<p>{{ $t('short_data.sub_selectLang') }}</p>
							<el-select v-model="gptForm.srtLang" placeholder="Select" @change="changeLang">
								<el-option
									v-for="item in gptForm.langList"
									:key="item.type"
									:label="item.label"
									:value="item.type"
								/>
							</el-select>
							<!-- <el-radio-group @change="changeLang" v-model="gptForm.srtLang">
								<el-radio label="en-US">{{ $t('short_data.subtitle.english') }}</el-radio>
								<el-radio label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-radio>
								<el-radio label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-radio>
								<el-radio label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-radio>
								<el-radio label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-radio>
							</el-radio-group> -->
					</div>
					<div class="form-group">
							<p>{{ $t('short_data.subtitle.transResult') }}</p>
							<el-input v-model="gptForm.transResultText" type="textarea" :rows="12" />
					</div>

				</div>
			</div>
      <template v-slot:footer>
        <div class="diaFooter">
          <el-button @click="gptForm.showContrast=false;showGptBox=false" :loading="gptForm.isLoading">{{$t('table_data.cancelText')}}</el-button>
          <el-button v-if="!gptForm.isTransEnd" @click="countinueAsk" :loading="gptForm.isLoading">{{ $t('short_data.sub_countinueAsk') }}</el-button>
          <el-button type="primary" @click="restartAsk" :loading="gptForm.isLoading">{{ $t('short_data.sub_newStartAsk') }}</el-button>
          <el-button @click="exportSrt" :loading="gptForm.isLoading">{{ $t('subtitle_data.explort') }}</el-button>
        </div>
      </template>
    </sCDialog>
		<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>
	</el-container>
</template>

<script>
import saveDialog from './client/save'
import sCDialog from "@/components/scDialog"

export default {
	name: "client",
	components: {
		saveDialog,
		sCDialog
	},
	data() {
		return {
			gptForm: {
				promptWord: 'The following content is in English SRT subtitle format text. Please translate it into Japanese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.',
				oldsrtLang: 'en-US',
				srtLang: 'ja-JP',
				srt: '',
				srtText: '',
				isLoading: false,
				words: [],
				langList: [
					{
						label: 'English',
						type: 'en-US'
					},
					{
						label: 'Japanese',
						type: 'ja-JP'
					},
					{
						label: 'French',
						type: 'fr-FR'
					},
					{
						label: '中文简体',
						type: 'zh-CN'
					},
					{
						label: '中文繁体',
						type: 'zh-TW'
					}
				],
				originalSrt: '',
				showContrast: false,
				isTransEnd: false,
				transResultText: ''
			},
			srtList: [],
			type: 0,
			showGptBox: false,
			direction: 'direction',
			langList: [
				{
					name: '简体中文',
					value: 'zh_CN',
				},
				{
					name: '繁體中文',
					value: 'zh_TW',
				},
				{
					name: 'English',
					value: 'en_US',
				},
				{
					name: '日本語',
					value: 'ja_JP',
				}
			],
			movieData: [

			],
			theatreData: [

			],
			dialog: {
				save: false
			},
			search: {
				keyword: ""
			},
			apiObj: null,
			selection: [],
			searchKey: null,
			params: {
				// currency: null,
				// movieId: null,
				// category: null,
				startDate: null,
				endDate: null,
				language: null
			},
			sendParams: {

			}
		}
	},
	computed: {
		setShortName(){
			return (e)=>{
				return e&&(e[this.$i18n.locale] || e['en_US']);
			}
		},
		oicon(){
			return function(e){
				return e
			}
		},
	},
	async created() {
		this.apiObj = this.$API.subtitle.getShorts;
		this.gptForm.words = this.$TOOL.data.get('word') || [];
		
	},
	methods: {
		exportSrt() {
			const blob = new Blob([this.gptForm.srtText], { type: 'text/plain' })
        
			// 创建下载链接
			const link = document.createElement('a')
			link.href = URL.createObjectURL(blob)
			link.download = `${this.gptForm.srtLang}_${new Date().getTime()}.srt`
			
			// 触发下载
			document.body.appendChild(link)
			link.click()
			// 清理
			setTimeout(() => {
				document.body.removeChild(link)
				URL.revokeObjectURL(link.href)
			}, 100)
		},
		submitData() {
			let data = {
				system: this.gptForm.promptWord,
				userChat: this.gptForm.srt,
			};
			if(!this.gptForm.originalSrt)this.gptForm.originalSrt = this.gptForm.srt;
			this.gptForm.isLoading = true;
			this.srtLang = this.gptForm.srtLang;
			if(this.gptForm.words.length > 10) {
				this.gptForm.words.unshift(this.gptForm.promptWord);
				this.gptForm.words.splice(10, 1);
			} else {
				this.gptForm.words.unshift(this.gptForm.promptWord);
			}
			this.$TOOL.data.set('word', this.gptForm.words);
			try {
				this.$API.ai.postAI.post(data).then(res => {
					// console.log('res', res);
					this.gptForm.isLoading = false;
					this.gptForm.transResultText = res.data||'';
					if(res.code == "OK" && res.data) {
						// this.showGptDialog = false;
						// this.showUploadBox = false;
						this.srtList = []
						// this.handlePop(4,false)
						this.gptForm.srtText = this.gptForm.srtText + res.data;
						this.handleSrt(this.gptForm.srtText);
					} else {
						this.$message.error('返回内容不是SRT格式字幕，请检查提示词和翻译内容');
					}
				})
			} catch (err) {
				console.warn(err);
				this.gptForm.isLoading = false;
			}
		},
		// 处理srt字幕
		handleSrt(str){
			let word = null;
			let isFG = str.includes('\r\n')?true:false;
			word = str.split('\n\n');
			if(isFG)word=str.split('\r\n\r\n')
			for(let i=0;i<word.length;i++){
				let nword = null;
				nword = word[i].split('\n');
				if(isFG)nword=word[i].split('\r\n')
				if(nword.length > 1 && nword[0] != "WEBVTT"){
					let etime = this.handTime(nword[1].split(' --> ')[1].split(':'))
					let stime = this.handTime(nword[1].split(' --> ')[0].split(':'))
					let label = nword.splice(2,nword.length-2).join('\n');
					this.srtList.push({
						index: nword[0].trim(),
						etime: nword[1].split(' --> ')[1].trim(),
						stime: nword[1].split(' --> ')[0],
						etimeStamp: etime,
						stimeStamp: stime,
						text: label
					})
				}
			}
		},
		handTime(etime){
			let h = parseInt(etime[0])*60*60;
			let m = parseInt(etime[1])*60;
			let s = parseInt(etime[2]?(etime[2].split('.').length==1?etime[2].split(','):etime[2].split('.'))[0]:'00');
			let hs = etime[2]?(etime[2].split('.').length==1?etime[2].split(','):etime[2].split('.'))[1]/1000:0;
			if(isNaN(h+m+s+hs)) {
				// this.$message.error('字幕格式错误，请检查后');
				console.warn("字幕格式错误");
			}
			return h+m+s+hs
		},
		// 上传文件解析为字符串
		inputSrtFileToString(event){
			let files = event.target.files;
			if(files.length > 1){
				this.$message.error(this.$t('components.upload.maxError'))
				return
			}
			if(!files[0].name.includes('srt') && !files[0].name.includes('ass')){
				this.$message.error(this.$t('short_data.subtitle.typeTips'))
				return
			}
			let reader = new FileReader();
			reader.readAsText(files[0])
			reader.onload = (res) => {
				this.gptForm.srt = res.target.result.replace(/\r/g,'');
				console.log('toString', res);
				event.target.value = '';
			}
		},
		initiateGPT() {
			this.showGptBox = true;
		},
		contrastSrt() {
			this.gptForm.showContrast = !this.gptForm.showContrast;
		},
		restartAsk() {
			this.gptForm.showContrast = false;
			this.type = 3;
			this.gptForm.srtText = '';
			this.gptForm.originalSrt = '';
			this.gptForm.isTransEnd = false;
			this.submitData()
		},
		countinueAsk() {
			this.gptForm.showContrast = false;
			let lastSrt = this.srtList[this.srtList.length-1];
			let sTime = lastSrt.stime;
			let eTime = lastSrt.etime;
			let index = lastSrt.index;
			let error1 = this.gptForm.srt.split(`${sTime}-->${eTime}`);
			let error2 = this.gptForm.srt.split(`${sTime} -->${eTime}`);
			let error3 = this.gptForm.srt.split(`${sTime}--> ${eTime}`);
			let right = this.gptForm.srt.split(`${sTime} --> ${eTime}`);
			if(error1.length > 1) {
				this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error1[1]}`;
			}
			if(error2.length > 1) {
				this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error2[1]}`;
			}
			if(error3.length > 1) {
				this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error3[1]}`;
			}
			if(right.length > 1) {
				this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${right[1]}`;
			}
			let srtSplitText = this.gptForm.srtText.split(`${index}\n${sTime} --> ${eTime}`);
			if(srtSplitText.length > 1) {
				try {
					let endText = this.gptForm.originalSrt.split(`${sTime} --> ${eTime}`)[1];
					if(endText.split('-->').length > 1) {
						this.gptForm.srtText = srtSplitText[0];
						this.submitData();
					} else {
						this.gptForm.isTransEnd = true;
						this.$message.success('已全部翻译完成');
					}
				} catch (error) {
					console.warn(error);
					this.$message.success('翻译文本内容识别错误，请修改后重新翻译');
				}
			} else {
				// this.gptForm.isTransEnd = true;
				// if(this.gptForm.isTransEnd)this.$message.success('已全部翻译完成');
				// else this.$message.error('翻译文本内容识别错误，请修改后重新翻译');
				this.$message.success('程序未响应，请检查是否已完成！');
				this.gptForm.srtText += '\n\n';
			}
			// console.log('继续提问', this.gptForm.srt, this.gptForm.srtText);
		},
		changeLang(e) {
			console.log('changeLang', e);
			if (e == 'ja-JP') {
				this.gptForm.promptWord = 'The following content is in English SRT subtitle format text. Please translate it into Japanese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
			} else if (e == 'en-US') {
				this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into English language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
			} else if (e == 'zh-CN') {
				this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into Simplified Chinese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
			} else if (e == 'zh-TW') {
				this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into Traditional Chinese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
			} else if (e == 'fr-FR') {
				this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into French language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
			}
		},
		closeTag(){
			const tagList = this.$store.state.viewTags.viewTags;
			const tag = this.$route;
			const nowTagIndex = tagList.findIndex(item => item.fullPath == tag.fullPath)
			this.$store.commit("removeViewTags", tag)
			this.$store.commit("removeIframeList", tag)
			this.$store.commit("removeKeepLive", tag.name)

			const leftView = tagList[nowTagIndex - 1]
			if (leftView) {
				this.$router.push(leftView)
			} else {
				this.$router.push('/')
			}
		},
		reset() {
			// this.params.currency = null;
			// this.params.movieId = null;
			// this.params.category = null;
			this.params.startDate = null;
			this.params.endDate = null;
			this.params.language = null;
			this.upsearch();
			// this.$refs.table.upData(this.params);
		},
		upsearch() {
			Object.assign(this.sendParams,this.params);
			if(this.sendParams.startDate)this.sendParams.startDate = this.$TOOL.getLocalTime(9,this.params.startDate,true)//this.$TOOL.dateFormat(this.sendParams.startDate);
			if(this.sendParams.endDate)this.sendParams.endDate = this.$TOOL.getLocalTime(9,this.params.endDate,true)//this.$TOOL.dateFormat(this.sendParams.endDate);
			this.$refs.table.upData(this.sendParams);
		},
		//增加
		add() {
			this.$router.push({path:'/brandTable/client/save',query:{type:'add','id':'add'}})
			// this.dialog.save = true
			// this.$nextTick(() => {
			// 	this.$refs.saveDialog.open()
			// })
		},
		//编辑
		table_edit(row){
			this.$router.push({path:'/brandTable/client/save',query:{type:'edit','id':row.brandId}})
			// this.dialog.save = true
			// this.$nextTick(() => {
			// 	this.$refs.saveDialog.open('edit').setData(row)
			// })
		},
		// 详情
		table_detail(row){
			this.$router.push({path:'/shortTable/subtitle/client/save',query:{type:'detail','id':row.dramaId}})
			// this.dialog.save = true
			// this.$nextTick(() => {
			// 	this.$refs.saveDialog.open('edit').setData(row)
			// })
		},
		//删除
		async table_del(row, index) {
			console.log(index)
			this.$confirm(this.$t('table_data.deltips1'), this.$t('table_data.tips'), {
				confirmButtonText: this.$t('table_data.editText'),
				cancelButtonText: this.$t('table_data.cancelText'),
				type: 'warning'
			}).then(async () => {
				var res = await this.$API.brand.delBrand.delete(row.brandId);
				if(res.code == 'OK'){
					//这里选择刷新整个表格 OR 插入/编辑现有表格数据
					this.$refs.table.upData(this.params);
					this.$message.success(this.$t('table_data.delsucc'))
				}else{
					this.$alert(res.message, this.$t('table_data.tips'), {type: 'error'})
				}
			}).catch(() => {
				// this.$message({
				// 	type: 'info',
				// 	message: 'cancel'
				// });          
			});
		},
		//批量删除
		async batch_del() {
			this.$confirm(`${this.$t('table_data.deltips1')} ${this.selection.length} ${this.$t('table_data.deltips2')}`, this.$t('table_data.tips'), {
				type: 'warning'
			}).then(() => {
				const loading = this.$loading();
				this.selection.forEach(item => {
					this.$refs.table.tableData.forEach((itemI, indexI) => {
						if (item.id === itemI.id) {
							this.$refs.table.tableData.splice(indexI, 1)
						}
					})
				})
				loading.close();
				this.$message.success(this.$t('table_data.operasucc'))
			}).catch(() => {

			})
		},
		//表格选择后回调事件
		selectionChange(selection) {
			this.selection = selection;
		},
		//本地更新数据
		handleSuccess(data, mode) {
			if (mode == 'add') {
				data.id = new Date().getTime()
				this.$refs.table.tableData.unshift(data)
			} else if (mode == 'edit') {
				this.$refs.table.tableData.filter(item => item.id === data.id).forEach(item => {
					Object.assign(item, data)
				})
			}
		},
		beforeOptions(v){
			if(!this.params.endDate)return false
			return v.getTime() > new Date(this.params.endDate).getTime();//  - 86400000是否包括当天
		},
		backOptions(v){
			return v.getTime() < new Date(this.params.startDate).getTime();//  - 86400000是否包括当天
		},
	}
}
</script>

<style scoped lang="scss">
.module-filter {
	margin-right: 10px;
}

.el-header {
	--el-header-height: auto;
}

.left-panel {
	flex-wrap: wrap;
	line-height: 50px;
}

.top-panel {
	margin: 10px;
}

.scTable {
	height: calc(100% - 60px) !important;
}

.el-main.nopadding {
	margin: 0 10px;
}

.el-header {
	margin: 10px;
	border-radius: 4px;
}
.gptheadbox {
	display: flex;
  justify-content: space-between;
}
	.diaFooter {
		display: flex;
		justify-content: center;
	}
	.gptCont {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
		.allSrtbox {
			position: absolute;
			width: 97%;
			height: 77%;
			background: #fff;
			z-index: 999;
			display: flex;
			.form-group {
				width: 50%;
				height: 100%;
			}
		}
		.gptleftbox {
			width: 49%;
			.form-group {
				border: 1px solid #dbdbdb;
				label {
					padding: 4px;
					color: #000;
				}
			}
		}
		.gptrightbox {
			width: 49%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			// max-height: 665px;
			.form-group {
				display: flex;
    		flex-direction: column;
				border: 1px solid #dbdbdb;
				margin-bottom: 10px;
				label {
					padding: 4px;
					color: #000;
				}
			}
			.el-radio-group {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
			}
		}
	}

@media only screen and (max-width: 820px) and (min-width: 768px) {
	.module-filter {
    flex: 0 0 30%;
    display: flex;
    flex-direction: column;
    margin: 0 10px;
	}
	.btns {
    margin: 10px;
    width: 340px;
    flex-direction: row;
	}
}
</style>
